package example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import example.vo.Link;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Log4j
@Service
public class BaseServiceImpl implements BaseService{

    @Override
    public void check() {
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        if (ossClient.doesBucketExist(Link.bucketName)) {
            log.info("您已经创建Bucket：" + Link.bucketName + "。");
        } else {
            log.info("您的Bucket不存在，创建Bucket：" + Link.bucketName + "。");
            ossClient.createBucket(Link.bucketName);
        }
        BucketInfo info = ossClient.getBucketInfo(Link.bucketName);
        log.info("Bucket " + Link.bucketName + "的信息如下：");
        log.info("\t数据中心：" + info.getBucket().getLocation());
        log.info("\t创建时间：" + info.getBucket().getCreationDate());
        log.info("\t用户标志：" + info.getBucket().getOwner());
        ossClient.shutdown();
        log.info("Completed");

    }

    @Override
    public void read() {
        log.info("Started");
        OSS ossClient = new OSSClientBuilder().build(Link.endpoint, Link.accessKeyId, Link.accessKeySecret);
        ObjectListing objectListing = ossClient.listObjects(Link.bucketName);
        List<OSSObjectSummary> objectSummary = objectListing.getObjectSummaries();
        log.info("您有以下Object：");
        for (OSSObjectSummary object : objectSummary) {
            log.info("\t" + object.getKey());
        }
        ossClient.shutdown();
        log.info("Completed");
    }


}
